package com.a.l;

import android.os.Build;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class MacUtils {
    public static String getEthMac() {
        String mac;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mac = getMacFromFile();
        } else {
            mac = getMacFromHardware();
        }
        if (mac == null || mac.isEmpty()){
            mac = "02:00:00:00:00:00";
        }
        return mac;
    }

    private static String getMacFromFile(){
        String wifiAddress = "02:00:00:00:00:00";
        try {
            wifiAddress = new BufferedReader(new FileReader(
                    new File("/sys/class/net/eth0/address"))).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wifiAddress;
    }

    private static String getMacFromHardware(){
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("eth0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "02:00:00:00:00:00";
    }
}
